<?php

class Order_Model extends Model {

    public function __construct() {
        parent::__construct();
        //echo "order_model";
    }


    public function getData() {

        //var_dump($_GET);
        $data = array('msg'=>'', 'list'=>null, 'userList'=>array());

        if(isset($_GET['orderId']) && !empty($_GET['orderId'])){
            $data['orderId'] = intval($_GET['orderId']);
            $data['count'] = 1;
            $data['validate'] = true;
            //var_dump($_POST);
            if (isset($_POST['action'])) {

                switch (strtolower($_POST['action'])) {

                    case 'add':
                        $data = $this->add($data);
                        break;
                    case 'addorderarticle':
                        $data = $this->addOrderArticle($data);
                        break;

                    case 'löschen':
                        if(isset($_POST['orderArticleId']) && is_array($_POST['orderArticleId'])){

                            $this->delorderArticle( $data['orderId'], $_POST['orderArticleId']);
                        }
                        break;
                    case 'export': //here is dummy to remove error msg
                        break;


                    default:
                        echo "error, unknown action!!";
                }
            }

            if ($data['validate']){
                $data['view'] = 'detail';

                //$data['orderId'] = intval($_GET['orderId']);
                $data['listArticle'] = $this->db->select("SELECT * FROM article");

                $sql = "SELECT * FROM article LEFT JOIN order_article ON article.id = order_article.article_id WHERE order_id = :id";

                $sth = $this->db->prepare($sql);

                //echo "3";
                $sth->execute(array(':id' => $data['orderId']));
                $einkauflist = $sth->fetchAll();
                //var_dump($einkauflist);
                $data['einkauflist'] = array();
                if (is_array($einkauflist) && count($einkauflist) > 0){
                    $data['einkauflist'] = $einkauflist;
                }

                if (isset($_POST['action']) && strtolower($_POST['action']) == 'export') {
                    $data = $this->exportCvs($data);
                }


            }else{

                $data['view'] = 'index';
                $data = $this->loadIndexData($data);

            }



        }else{




            if (isset($_POST['action'])) {
                switch (strtolower($_POST['action'])) {
                    case 'löschen':
                        $this->del();
                        break;
                    case 'packen':
                        //$this->setStatus(Database::$Park, $data);
                        break;
                    case 'abgesendet':
                        $this->setStatus(Database::$AUS, $data);
                        break;
                    case 'add':
                        $data = $this->add($data);
                        break;
                    default:
                        echo "error, unknow action!!";
                }

            }



            $data = $this->loadIndexData($data);
        }


        return $data;
    }


    protected function  loadIndexData($data){
        $sth = $this->db->prepare("SELECT * FROM `user` WHERE name NOT IN ('chen', 'jessica') ");
        //echo "3";
        $sth->execute();
        $data['userList'] = $sth->fetchAll();


        $max = $this->db->select("SELECT MAX(id) FROM `order`");
        //var_dump($max);
        if(is_array($max) && count($max)){
            $res = array_values($max[0]);
            $data['nextOrderId'] = $res[0]+1;
        }else{
            $data['nextOrderId'] = 1;
        }


        $data['view'] = 'index';

        $data['list']=$this->getorderList();
        $sql = "SELECT * FROM `order` WHERE `lock`='".Database::$Nein."' ORDER BY create_time DESC";
        try{
            $data['list'] = $this->db->select($sql);
        }catch (PDOException $e){
            echo $e->getMessage();
        }

        return $data;
    }

    protected function processOrderInput(){
        $inputData = array('validate' => true);
        $fieldSet = Database::$orderFieldSet;
        $fieldSet['Verpacker'] = 'packer';
         //$fieldSet =   array('Order-Nr' =>'order_code', 'Packet-Nr'=>'package_code', 'Package Preis(Euro)'=> 'shipping_price_e','Adresse'=>'adress',
         //   'Wechselkurs'=> 'exchange_rate', 'Verpackungsgebühr'=>'package_price_e', 'Faktor'=>'factor', 'Kommentar'=>'comment', 'Verpacker'=>'packer');
        //var_dump(array_diff($fieldSet, Helper::$orderFieldSet));
        $inputFields = array_values($fieldSet);
        //var_dump($_POST);
        foreach($inputFields AS $key){
            if(isset($_POST[$key]) && !empty($_POST[$key])){
                $inputData[$key] = trim($_POST[$key]);
            }else{
                $inputData[$key]  = '';
                //echo "ni ma ni!".$key;
                if ($key != 'comment')
                $inputData['validate'] = false;
            }
        }
        if ($inputData['validate']){
            $dTime = new DateTime();
            $createTime = $dTime->format(Database::$TimeFormat);
            $initSet = array('price_e'=>0, 'price_y'=>0, 'create_time'=>$createTime,'out_time'=>$createTime, 'order_status'=>Database::$Park, 'lock'=>Database::$Nein);
            $inputData = array_merge($inputData, $initSet);
        }
        //var_dump($inputData);
        return $inputData;

    }

    protected  function add($data){

        /*
        $userName = trim($_POST['userName']);
        $comment = trim($_POST['comment']);


        $sth = $this->db->prepare("SELECT * FROM user WHERE id = :userId");
        $sth->execute(array(':userId' => $userId));
        $userName = '';
        $aUser = $sth->fetchAll();


        if (is_array($aUser) && count($aUser) > 0){
            $userName = $aUser[0]['name'];

        }*/

        $inputData = $this->processOrderInput();
        if( $inputData['validate']){
            try{
                $data['validate'] = $inputData['validate'];
                unset($inputData['validate']);
                //var_dump($inputData);
                $id = $this->db->insert('`order`', $inputData);

                $data['msg'] = '<div class="successMsg">'.filter_var($inputData['order_code'], FILTER_SANITIZE_STRING) .' | '.filter_var($inputData['package_code'], FILTER_SANITIZE_STRING) .' | '.filter_var($inputData['adress'], FILTER_SANITIZE_STRING) .' wurde angelegt.</div>';


            }catch (PDOException $e) {
                echo 'Exception: order cannot be inserted: ',  $e->getMessage(), "\n";
            }
        }else{
            $data['msg'] = '<div class="errorMsg">Der Vertrag kann nicht anlegen. Bitte füllen alle Field aus.</div>';
        }
        $data = array_merge($data,$inputData);
        //var_dump($data);

        return $data;
    }

    protected  function del(){
        if(isset($_POST['orderId']) && is_array($_POST['orderId'])){
            $where = "id IN (".implode(' ,', $_POST['orderId']).")";
            $dTime = new DateTime();
            $lockTime = $dTime->format(Database::$TimeFormat);

            $this->db->update('`order`', array('lock'=>Database::$JA, 'lock_time'=>$lockTime),$where);
            $this->updateCurrentStock(false);//change to set old preis
        }

    }

    protected  function getorderList(){
        $list = array();
        $sql = "SELECT * FROM `order` WHERE `lock`='".Database::$Nein."' ORDER BY create_time DESC";
        try{
            $list = $this->db->select($sql);
        }catch (PDOException $e){
            echo $e->getMessage();
        }
        return $list;

    }

    protected  function setStatus($status, &$data){
        if(isset($_POST['orderId']) && is_array($_POST['orderId'])){
            $this->updateCurrentStock();
            $idList = $this->getPackOrderIdList($_POST['orderId']);
            //var_dump($idList);
            if (!$this->hasEnoughStock($idList)){
                $data['msg'] = '<div class="errorMsg">Achtung, in Lager gibt es keinen genügend Artikeln!!</div>';
                return;
            }
            $where = "id IN (".implode(' ,', $idList).")";
            $dTime = new DateTime();
            $dateTime = $dTime->format(Database::$TimeFormat);



            //set durchschnitt price
            $this->updateOrderArticlePrice($idList);
            $this->db->update('`order`', array('order_status'=>$status, 'out_time'=>$dateTime), $where);
            $this->updateCurrentStock();
        }

    }

    protected  function  updateOrderArticlePrice($idList){
        $sql = "SELECT * FROM `order_article` WHERE"." `order_id` IN (".implode(' ,', $idList).")";
        //echo $sql;

        $sth = $this->db->prepare($sql);
        $sth->execute();
        $orderArticleList = $sth->fetchAll();
        foreach ($orderArticleList AS $article){
            $price = $this->loadCurrentStockArticlePrice($article['article_id']);
            //echo '<hr> price';
            //var_dump($price);
            //var_dump($article);
            $where = "`id`='".$article['id']."'";


            //here is copy of db->update, because this bull shit db, mal so mal so
            //kann nie richtig work
            //var_dump("UPDATE `order_article` SET recommend_price = ".$price." WHERE $where");
            $sth = $this->db->prepare("UPDATE `order_article` SET recommend_price = ".$price." WHERE $where");
            $sth->execute();

            //$this->db->update('`order_article`', array('﻿recommend_price'=>$price), $where);
        }

    }

    protected function hasEnoughStock($idList){
        $hasEnoughStock = false;
        $max = $this->db->select("SELECT MAX(id) FROM stock");
        //var_dump($max);
        if(is_array($max) && count($max)){
            $res = array_values($max[0]);

            $sth = $this->db->prepare("SELECT * FROM `stock_article`  WHERE `stock_id` = :id");

            $sth->execute(array(':id' => $res[0]));
            $stock = $sth->fetchAll();
            //var_dump($stock);
            //echo "<hr />";
            $stockArticleCountList = array();
            foreach ($stock AS $article){
                if (array_key_exists($article['article_id'], $stockArticleCountList)){
                    $stockArticleCountList[$article['article_id']] += $article['count'];

                }else{
                    $stockArticleCountList[$article['article_id']] = $article['count'];
                }
            }
            //var_dump($stockArticleCountList);
            //echo "<hr />order id list";

            // load order article
            $sql = "SELECT * FROM `order_article` WHERE"." `order_id` IN (".implode(' ,', $idList).")";
            //echo $sql;

            $sth = $this->db->prepare($sql);
            $sth->execute();
            $orderList = $sth->fetchAll();
            //var_dump($orderList);
            //echo "<hr />";
            $ArticleCountList =  array();
            foreach ($orderList AS $order){
                if (array_key_exists($order['article_id'], $ArticleCountList)){
                    $ArticleCountList[$order['article_id']] += $order['count'];

                }else{
                    $ArticleCountList[$order['article_id']] = $order['count'];
                }
            }
            //var_dump($ArticleCountList);
            //echo "<hr />";

            foreach($ArticleCountList AS $articleId => $count){
                if(array_key_exists($articleId, $stockArticleCountList) && $stockArticleCountList[$articleId] >= $count){
                    continue;
                } else{

                    return false;
                }

            }

            $hasEnoughStock = true;
        }
        return $hasEnoughStock;

    }


    protected function getPackOrderIdList($idList){
        //return $idList;
        $sql = "SELECT `id` FROM `order` WHERE `id` IN (".implode(' ,', $idList).") AND `order_status` = '".Database::$Park."'";
        $sth = $this->db->prepare($sql);
        $sth->execute();
        $orderIdList = $sth->fetchAll();

        $idList = array();
        foreach ($orderIdList AS $orderId){
            $idList[] = $orderId['id'];
        }


        return $idList;
    }

    protected  function delorderArticle($orderId, $orderArticleIds){
        //var_dump($_POST);
        //get total price of removing article

        $idList = " WHERE `id` IN (".implode(' ,', $orderArticleIds).")";
        $sql = "SELECT  SUM( total_price_e ) AS totalprice FROM `order_article`".$idList;
        /** @var $sth PDOStatmen */
        //echo $sql;
        $sth = $this->db->select($sql);
        if (count($sth) > 0){
            $diffPrice = round($sth[0]['totalprice'], 2);
            //var_dump($sth);
            $this->updatePrice($orderId, $diffPrice*(-1));

            $where = "id IN (".implode(' ,', $orderArticleIds).")";

            //echo $where;
            $this->db->delete('`order_article`', $where, 50);
        }else{
            throw new Exception('Error, the ids can not be found in order_article!');
        }


    }


//article_id, supplier,count,price_e
    protected  function addorderArticle($data){
        $bAllowWrite = true;
        $data['ean'] = '';
        $data['count'] = 1;
        if (isset($data['count']) && !empty($_POST['count'])){
            $data['count'] = intval($_POST['count']);
        }

        if (isset($_POST['ean']) && !empty($_POST['ean'])){
            $ean = filter_var(trim($_POST['ean']), FILTER_SANITIZE_STRING);
            $sth = $this->db->prepare("SELECT * FROM article WHERE ean = :ean");
            //echo "3";
            $sth->execute(array(':ean' => $ean));
            $article = $sth->fetch();
            if ($sth->rowCount() > 0){
                $data['ean'] =$ean;
                $data['article_id'] = $article['id'];
                $data['article_name'] = $article['name_de'];

                $postSet = array('supplier', 'price_e', 'count');
                foreach ($postSet As $postData){
                    if (isset($_POST[$postData]) && !empty($_POST[$postData])){
                        $data[$postData] = $_POST[$postData];
                    }else{
                        $data[$postData]  = '';
                        if($postData != 'supplier')
                            $bAllowWrite = false;
                    }
                }

            }
            else{

                $data['msg'] = '<div class="errorMsg"> Diese EAN Nr. '.$ean.' ist unbekannt! Bitte zuerst anlegen, dann versuchen Sie noch mal.</div>';

                $bAllowWrite = false;
                $postSet = array('article_id', 'supplier', 'price_e', 'count');
                foreach ($postSet As $postData){
                    if (isset($_POST[$postData]) && !empty($_POST[$postData])){
                        $data[$postData] = $_POST[$postData];
                    }else{
                        $data[$postData]  = '';
                    }
                }



            }
        }else{
            $postSet = array('article_id', 'supplier', 'price_e', 'count');
            foreach ($postSet As $postData){
                if (isset($_POST[$postData]) && !empty($_POST[$postData])){
                    $data[$postData] = $_POST[$postData];
                }else{
                    $data[$postData]  = '';
                    if($postData != 'supplier')
                        $bAllowWrite = false;
                }
            }

        }

        if (isset($_POST['loadprice']) && strtolower($_POST['loadprice']) =='preisvorschlag'){
            $bAllowWrite = false;
        }
        //var_dump($_POST);

        if ($bAllowWrite){
            //get article name, here is just for rend msg info
            $sth = $this->db->prepare("SELECT * FROM article WHERE id = :id");
            //echo "3";
            $sth->execute(array(':id' => $data['article_id']));
            $textArticle = $sth->fetch();
            if ($sth->rowCount() > 0){
                //echo "4";
            }


            $total = $data['count'] * $data['price_e'];

            //echo "==========";
            //var_dump($data['count'] * $data['price_e']);
            $id = $this->db->insert('`order_article`', array('order_id'=>$data['orderId'], 'article_id'=>$data['article_id'], 'price_e'=>$data['price_e'], 'count'=>$data['count'], 'total_price_e'=>$total));



            $data['msg'] = '<div class="successMsg">'.$textArticle['name_de'] .': '.$data['price_e'].' X '.$data['count'].' = '.$total. '  EURO</div>';
            //nach der speichern reset daten
            $postSet = array('article_id', 'supplier', 'price_e', 'count', 'ean');
            foreach ($postSet As $postData){
                $data[$postData]  = '';
            }

            //update order.total_price_e
            $this->updatePrice($data['orderId'], $total);

        }else{

            $data = $this->loadPrice($data);
        }


        return $data;

    }

    protected function updatePrice($id, $price){
        //if (is_array($id) && count($id)>0){
        $sth = $this->db->prepare("SELECT * FROM `order` WHERE id = :id");
        //echo "3";
        $sth->execute(array(':id' => $id));
        $res = $sth->fetchAll();
        //var_dump($res);
        if ($sth->rowCount() > 0){

            if ($price > 0){
                if ($res[0]['price_e'] > 0){
                    $currentPrice = $price+$res[0]['price_e'];
                }else{
                    $currentPrice = $price+$res[0]['price_e'] + $res[0]['shipping_price_e'] + $res[0]['package_price_e'];
                }

            }else{
                $tempPrice = $price+$res[0]['price_e'] - $res[0]['shipping_price_e'] - $res[0]['package_price_e'];
                if ($tempPrice <= 0){
                    $currentPrice = 0;
                }else{
                    $currentPrice = $price+$res[0]['price_e'];
                }

            }

            //echo "currentPrice:".$currentPrice;
            //echo "--price:".$price;
            //echo "--alter:".$res[0]['price_e'];
            //echo "--yuan:".$res[0]['price_e'];
            if ( $currentPrice >=  0){
                $totalYuan = $currentPrice * $res[0]['exchange_rate'];
                $this->db->update('`order`', array('price_e'=>$currentPrice, 'price_y'=>$totalYuan), "`id`='".$id."'");
            }else{
                throw new Exception("Error, total price is already 0!!");
            }
        }

    }


    protected function loadPrice($data){

        $hasError = true;
        if (isset($data['article_id']) && !empty($data['article_id'])){
            $max = $this->db->select("SELECT MAX(id) FROM stock");
            //var_dump($max);
            $stockId  = '';
            if(is_array($max) && count($max)){
                $res = array_values($max[0]);
                $stockId  = $res[0];
                $this->updateStock($stockId);
            }

            if (!empty($stockId)){
                $sql = "SELECT * FROM stock_article  WHERE stock_id = :id AND article_id = :articleId";

                $sth = $this->db->prepare($sql);

                //echo "3";
                $sth->execute(array(':id' =>$stockId, ':articleId'=>$data['article_id']));
                $stockArticle = $sth->fetch();
                //var_dump($stockArticle);
                if (is_array($stockArticle) && count($stockArticle) > 0 ){
                    $sql = "SELECT * FROM `order` WHERE id = :orderId";

                    $sth = $this->db->prepare($sql);

                    //echo "3";
                    $sth->execute(array(':orderId' =>$data['orderId']));
                    $order = $sth->fetch();
                    $factor = floatval($order['factor']);

                    //var_dump($stockArticle);
                    if (is_array($stockArticle) && intval($stockArticle['count']) > 0 && !empty($factor)){
                        $data['price_e'] = Helper::roundUp($stockArticle['price_e']*$factor, 2);
                        $hasError = false;

                    }

                }

            }



        }else{
           echo  "no article id";
        }
        if ($hasError){
            $data['msg'] .= '<div class="errorMsg">Achtung, der Artikel hat keinen Preisvorschlag </div>';

        }


        return $data;
    }

    protected function loadCurrentStockArticlePrice($articleId){
        $price = 0;

        $max = $this->db->select("SELECT MAX(id) FROM stock");
        //var_dump($max);
        $stockId  = '';
        if(is_array($max) && count($max)){
            $res = array_values($max[0]);
            $stockId  = $res[0];
            $this->updateStock($stockId);
        }

        if (!empty($stockId)){
            $sql = "SELECT * FROM stock_article  WHERE stock_id = :id AND article_id = :articleId";

            $sth = $this->db->prepare($sql);


            $sth->execute(array(':id' =>$stockId, ':articleId'=>$articleId));
            $stockArticle = $sth->fetch();
            //var_dump($stockArticle);
            if (is_array($stockArticle) && intval($stockArticle['count']) > 0 ){
               $price = $stockArticle['price_e'];
            }
        }
        return $price;
    }


    protected function exportCvs($data, $tpl ='', $content =''){

        $content = '';
        //export order data

        $sql = "SELECT * FROM `order` WHERE `lock`='".Database::$Nein."' AND id=".$data['orderId'];
        $orderData = $this->db->select($sql);
        //var_dump($orderData);
        //die();
        $fieldSet = Database::$orderFieldSet;
        foreach ( $fieldSet AS $key =>$val ) {
            $content .=  $key.Database::$cvsDelimiter.$orderData[0][$val]."\n";
        }
        $content .= "\n";
        $content .= "\n";


        //export article list
        $content .= implode( Database::$cvsDelimiter, array_keys( Database::$orderArticleSet ) );
        $content .= "\n";
        $list = $data['einkauflist'];
        $fieldSet = array_values( Database::$orderArticleSet );

        foreach ( $list AS $item ) {
            $cnt = 1;
            foreach ( $fieldSet AS $field ) {
                $delimiter = Database::$cvsDelimiter;
                if ($cnt == count($fieldSet)){
                    $delimiter = "\n";
                }
                $content .=  $item[$field].$delimiter;
                $cnt++;
            }
        }

        $data['view'] = 'export';
        Helper::download_send_headers('views/order/export_tpl.php', $content, "verkauf");
        return $data;
    }




}